package com.example.kaptcha.controller;

import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Date;

@RestController
@RequestMapping("/admin")
public class KaptchaController {
    private final String  KAPTCHA_SESSION_KEY="KAPTCHA_SESSION_KEY";
    private final String  KAPTCHA_SESSION_DATE="KAPTCHA_SESSION_DATE";
    private final long  TIME_OUT=60*1000;
    @RequestMapping("/check")
    public boolean check(String inputCaptcha, HttpSession session) {
        //这里首先先校验验证码是否为空
        //然后在进行验证时间的问题
        System.out.println("请求发送的验证码："+inputCaptcha);
        if(!StringUtils.hasLength(inputCaptcha)) {
            return false;
        }
        String saveKaptcha = (String) session.getAttribute(KAPTCHA_SESSION_KEY);
        Date saveDate = (Date) session.getAttribute(KAPTCHA_SESSION_DATE);

        if(inputCaptcha.equalsIgnoreCase(saveKaptcha)) {
            if(saveDate!=null || System.currentTimeMillis()-saveDate.getTime()<TIME_OUT) {
                return true;
            }
        }
        return false;
    }
}
